package test.transferFile3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.handler.stream.StreamIoHandler;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
 * 文件传输服务器，把接收到的文件写到本地
 * 
 * @author Simple
 * @date 2013-6-24 上午11:57:06
 * @Description TODO
 */
public class FileServer extends StreamIoHandler {

  public static final int PROT=9999;

  @Override
  protected void processStreamIo(IoSession session, InputStream in, OutputStream out) {
    System.out.println("invoke processStreamIo()");
    // 设定一个线程池(最少数量3，最大数量6，空闲时间3s，缓冲队列为3，抛弃旧任务)
    ThreadPoolExecutor threadPool=
      new ThreadPoolExecutor(3, 6, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
        new ThreadPoolExecutor.DiscardOldestPolicy());
    FileOutputStream fos=null;
    File receiveFile=new File("e:\\test.txt");
    try {
      fos=new FileOutputStream(receiveFile);
    } catch(FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    threadPool.execute(new IoStreamThreadWork(in, fos));
  }

  public void createServerStream() {
    NioSocketAcceptor acceptor=new NioSocketAcceptor();
    DefaultIoFilterChainBuilder chain=acceptor.getFilterChain();
    ObjectSerializationCodecFactory factory=new ObjectSerializationCodecFactory();
    // 设定服务器接收数据大小
    factory.setDecoderMaxObjectSize(Integer.MAX_VALUE);
    factory.setEncoderMaxObjectSize(Integer.MAX_VALUE);
    
    chain.addLast("log", new LoggingFilter());
    // 设置handler
    acceptor.setHandler(new FileServer());
    try {
      acceptor.bind(new InetSocketAddress(PROT));
      System.out.println("server started");
    } catch(IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    FileServer fileServer=new FileServer();
    fileServer.createServerStream();
  }
}
